package controller

import (
	"01/dbconnect"
	"01/models"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strconv"
)

type Test struct {
	gorm.Model
	ID   int
	List string
	Age  int
}

func Index(c *gin.Context) {
	//db := dbconnect.Db
	// 查询单个记录
	//var test Test
	//if err := db.First(&test).Error; err != nil {
	//	// 处理查询错误
	//	return
	//}

	// 查询多个记录
	//var tests []Test
	//if err := db.Find(&tests).Error; err != nil {
	//	// 处理查询错误
	//	return
	//}
	id, _ := strconv.Atoi(c.Query("id"))

	tests, _ := models.Test{}.GetTestAll(id)
	ReturnSuccess(c, 0, "success", tests, 1)

}

// Insert
// @Description 添加数据
// @Author Faiz 2023-12-03 20:31:19
func Insert(c *gin.Context) {
	//Age := c.Query("id")
	List := c.Query("name")
	test := Test{List: List}
	db := dbconnect.Db
	db.AutoMigrate(Test{List: List})
	result := db.Create(&test) // 通过数据的指针来创建
	fmt.Println(result)
	if result != nil {
		fmt.Println("测试")
	}
	ReturnSuccess(c, 0, "success", result, 1)
}

func Update(c *gin.Context) {
	id := c.Query("id")
	List := c.Query("name")
	//fmt.Println(Age)
	//fmt.Println(List)
	var test Test
	//db := dbconnect.Db
	//
	//db.First(&test, id)
	test.List = List
	test.Age, _ = strconv.Atoi(id)
	ids, _ := strconv.Atoi(id)
	//tests := db.Save(&test) //会更新所有的字段
	tests, _ := models.Test{}.Update(ids, List)
	ReturnSuccess(c, 0, "success", tests, 1)
}

func Delete(c *gin.Context) {
	//db := dbconnect.Db
	//tests := db.Delete(&Test{}, 90)
	//ReturnSuccess(c, 0, "success", tests, 1)
	id, _ := strconv.Atoi(c.Query("id"))
	tests, _ := models.Test{}.Delete(id)
	ReturnSuccess(c, 0, "success", tests, 1)
}
